package swing.solutions;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class SwingTableModelExercise extends JFrame{
	
	
	class MyTableModel extends AbstractTableModel{
		
		class MyTableRow{
			String name;
			Date date;
			Integer id;
			Boolean flag;
		}
		
		private List<MyTableRow> rows = new ArrayList<MyTableRow>();
		
		public MyTableModel() {
			for (int i = 0; i < getRowCount(); i++) {
				MyTableRow row = new MyTableRow();
				row.name = "Row "+i;
				row.date = new Date();
				row.id = i;
				row.flag = (i % 3 == 0)? true : false;
				rows.add(row);
			}
		}
		
		
		public String getColumnName(int column) {return "Column " + column;}

		public int getRowCount() {return 10;}

		public int getColumnCount() {return 4;}

		public boolean isCellEditable(int row, int col) {
			if(col == 1) return false;
			return true;
		}
		
		public Object getValueAt(int rowIndex, int columnIndex) {
			MyTableRow row = rows.get(rowIndex);
			if(columnIndex == 0){
				return row.name;
			}
			if(columnIndex == 1){
				return row.date;
			}
			if(columnIndex == 2){
				return row.id;
			}
			if(columnIndex == 3){
				return row.flag;
			}
			return "Undefined";
		}
		
		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			MyTableRow row = rows.get(rowIndex);
			if(columnIndex == 0){
				row.name = (String) aValue;
			}
			if(columnIndex == 1){
				//editing dates not supported
			}
			if(columnIndex == 2){
				row.id = (Integer) aValue;
			}
			if(columnIndex == 3){
				row.flag = (Boolean) aValue;
			}
		}
		
		public Class<?> getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}
		
	}
	
 
	
	public SwingTableModelExercise() {
		setTitle("My Frame"); 
		setSize(400, 150); 
		setLocationRelativeTo(null);
		JTable table = new JTable(new MyTableModel());
		table.setPreferredScrollableViewportSize(new Dimension(500, 70));
		table.setFillsViewportHeight(true);
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane);
		pack();
		setVisible(true); 
	}

	public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
		UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
		new SwingTableModelExercise();
	}

}

